package tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@MultipartConfig(fileSizeThreshold = 1024*1024*2,//2MB
        maxFileSize = 1024*1024*10,//10MB
        maxRequestSize = 1024*1024*50)//50MB
public class UploadFileTool extends HttpServlet {
    public String UploadImage(HttpServletRequest request,String save_directory) throws ServletException, IOException {
        Part filePart=request.getPart("certifi");//获取上传文件的Part对象
        String fileName=getFileName(filePart);//获取上传文件的原始文件名
        String savePath=request.getServletContext().getRealPath("")+ File.separator+save_directory;//获取保存文件的目录路径
        File saveDir=new File(savePath);//创建保存文件的目录
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        filePart.write(savePath+File.separator+fileName);//创建保存的文件

        return savePath;
    }
    private  String getFileName(Part part){
        String contentDisposition=part.getHeader("content-disposition");
        String[] elements=contentDisposition.split(";");
        for(String element:elements){
            if(element.trim().startsWith("filename")){
                return element.substring(element.indexOf('=')+1).trim().replace("\"","");
            }
        }
        return "";
    }
}
